<?php

/**
 * Created by PhpStorm.
 * User: tei
 * Date: 2019/7/28
 * Time: 8:01 PM
 */

namespace app\index\controller;

use app\index\model\Domain;
use app\index\model\User;
use app\index\model\Agents;
use app\index\model\System;

use think\Cache;
use think\Request;
use think\Session;
use think\Db;
use app\index\common;

class Login
{

    /**
     * @function 登陆页面
     */
    public function login_view()
    {
        $sys_info = Domain::where('type', 11)->field('domain')->find();
        $title = $sys_info['domain'];
        $domain = 'http://' . $_SERVER['HTTP_HOST'];
        return view('login/login', [
            'title' => $title,
            'domain' => $domain
        ]);
    }

     /**
     * @function 获取logo接口
     */
    public function getlogo(){
        $sys_info = Domain::where('type', 32)->field('domain')->find();
        return ['code' => 200, 'msg' => '获取成功', 'data' => $sys_info['domain']];
    }

    /**
     * @function 微信登陆页面
     */
    public function wx_login_view()
    {
        //获取微信授权域名 appid appsecret
        $authdomain = Domain::where('type', 21)->field('domain')->find();
        $redirectdomain = Domain::where('type', 24)->where('status', 0)->field('domain')->find();
        $appid = Domain::where('type', 22)->field('domain')->find();

        $domain = 'http://' . $authdomain['domain'];

        $request = Request::instance();
        $agent_id = $request->get('agent_id');
        $clearUser = empty($request->get('clearUser')) ? 0 : $request->get('clearUser');

        return view('login/wx_login', [
            'appid' => $appid['domain'],
            'domain' => $domain,
            'agent_id' => $agent_id,
            'clearUser' => $clearUser,
            'redirectdomain' => $redirectdomain['domain'],
        ]);
    }

    /**
     * @function 检测微信浏览器
     *
     */

    function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

    public function wx_login_view_quick()
    {
        $request = Request::instance();
        $agent_id = $request->get('agent_id');
        $clearUser = empty($request->get('clearUser')) ? 0 : $request->get('clearUser');

        $redirectdomain = Domain::where('type', 24)->where('status', 0)->field('domain')->find();

        if ($this->is_weixin()) {
            return view('login/wx_login_quick', [
                'url' => '/v1/login/wx_login?clearUser+' . $clearUser . '!agent_id+' . $agent_id,
                'redirectdomain' => $redirectdomain['domain'],
            ]);
        } else {
            return view('login/wx_login_phone', [
                'agent_id' => $agent_id,
                'redirectdomain' => $redirectdomain['domain'],
            ]);
        }
    }

    /**
     * @function 微信redirect 业务域名
     *
     */

    // public function wx_login_redirect(){
    //     // $redirectdomain = Domain::where('type', 24)->field('domain')->find();


    //     // $title = $redirectdomain['domain'];
    //     // $domain = 'http://' . $redirectdomain['domain'];
    //     // $query = $_SERVER['QUERY_STRING'];

    //     $request = Request::instance();
    //     $domain = $request->get('redirectdomain');
    //     $code = $request->get('code');
    //     $agent_id = $request->get('agent_id');
    //     return view('login/wx_login_redirect', [
    //         'url' => 'http://'.$domain.'?code='.$code.'&agent_id='.$agent_id
    //     ]);
    // }

    public function domainInfo()
    {
        $request = Request::instance();
        $uid = $request->post('uid');
        $member = User::where('uid', $uid)->field('head,name,score,integral,xm_rate,phone')->find();
        $roomsnosay = System::where('nosay', 1)->field('groupid')->select();
        $roomsnosaystr = [];
        if (!empty($roomsnosay)) {
            foreach ($roomsnosay as $item) {
                array_push($roomsnosaystr, $item['groupid']);
            }
        }
        $sys_info = Domain::whereIn('type', [11, 8, 12, 10, 27])->field('domain,type,status')->select();
        $title = "腾龙国际";
        $head_domain = "";
        $wsurl = "";
        $game_rule_text = "";
        $notice = "";
        foreach ($sys_info as $item) {
            if ($item['type'] == 11) {
                $title = $item['domain'];
            }
            if ($item['type'] == 8) {
                $head_domain = $item['domain'];
            }
            if ($item['type'] == 12) {
                $wsurl = $item['domain'];
            }
            if ($item['type'] == 10) {
                $notice = $item['domain'];
                $notice_status = $item['status'];
            }
            if ($item['type'] == 27) {
                $imcode = $item['domain'];
            }
        }
        $real_ip = empty($_SERVER['HTTP_X_REAL_IP']) ? $request->ip() : $_SERVER['HTTP_X_REAL_IP'];
        $ip_data_json = common::http_request("http://ip.taobao.com/service/getIpInfo.php?ip=" . $real_ip, null, 3);
        $logindata = [
            'wsurl' => $wsurl,
            'title' => $title,
            'imcode' => $imcode,
            'notice' => $notice,
            'notice_status' => $notice_status,
            'ip_info' => $ip_data_json,
            'ip' => $real_ip,
            'head' => $member['head'],
            'phone' => $member['phone'],
            'name' => $member['name'],
            'score' => $member['score'],
            'integral' => $member['integral'],
            'xm_rate' => $member['xm_rate'],
            'head_domain' => $head_domain,
            'roomsnosay' => implode(",", $roomsnosaystr)
        ];
        return ['code' => 200, 'msg' => '获取成功', 'data' => $logindata];
    }

    public function wx_login_auth_token()
    {
        $request = Request::instance();
        $token = $request->post('token');
        if (empty($token) && $token != NULL) {
            return ['code' => 500, 'msg' => 'token登录失败', 'data' => null];
        } else {
            $member = User::where('token', $token)->find();
            if (empty($member)) {
                return ['code' => 500, 'msg' => 'token登录失败', 'data' => null];
            } else {
                cookie('uid', $member['uid']);
                Session::set('uid', $member['uid']);
                $success = TRUE;
                $uid = $member['uid'];
                if ($success) {
                    User::where('uid', $uid)->update(['token' => NULL]);//更新个人信息
                    $sys_info = Domain::whereIn('type', [11, 8, 12, 9, 10, 12, 27, 30])->field('domain,type,status')->select();
                    $title = "腾龙国际";
                    $head_domain = "";
                    $wsurl = "";
                    $game_rule_text = "";
                    $notice = "";
                    $imcode = "";
                    $user_type = 3;
                    foreach ($sys_info as $item) {
                        if ($item['type'] == 11) {
                            $title = $item['domain'];
                        }
                        if ($item['type'] == 8) {
                            $head_domain = $item['domain'];
                        }
                        if ($item['type'] == 12) {
                            $wsurl = $item['domain'];
                        }
                        if ($item['type'] == 30) {
                            $qrcode = $item['domain'];
                        }
                        if ($item['type'] == 9) {
                            $game_rule_text = $item['domain'];
                        }
                        if ($item['type'] == 10) {
                            $notice = $item['domain'];
                            $notice_status = $item['status'];
                        }
                        if ($item['type'] == 27) {
                            $imcode = $item['domain'];
                        }
                    }
                    $member = Db::name('user')->field('username,name,uid,head,password,score,password,agents_id,agents_account,agents_name,xm_rate,integral')->where('uid', $uid)->find();
                    $member['nickname'] = $member['name'];
                    if (!empty($member['head'])) {
                        $member['head'] = $member['head'];
                    }
                    $real_ip = empty($_SERVER['HTTP_X_REAL_IP']) ? $request->ip() : $_SERVER['HTTP_X_REAL_IP'];
                    $ip_data_json = common::http_request("http://ip.taobao.com/service/getIpInfo.php?ip=" . $real_ip, null, 3);
                    $ip_data = json_decode($ip_data_json, true);
                    if ($user_type != 1) {
                        $insert_data = [
                            'uid' => $uid,
                            'username' => $member['username'],
                            'name' => $member['name'],
                            'user_type' => 0,
                            'ip_info' => empty($ip_data['data']) ? "" : json_encode($ip_data['data']),
                            'ip' => $real_ip,
                            'mktime' => time(),
                            'agents_id' => $member['agents_id'],
                            'agents_account' => $member['agents_account'],
                            'agents_name' => $member['agents_name']
                        ];
                        Db::name('user_login_info')->insert($insert_data);
                    }
                    $time = time();
                    $domain = 'http://' . $_SERVER['HTTP_HOST'];
                    $roomsnosay = System::where('nosay', 1)->field('groupid')->select();
                    $roomsnosaystr = [];
                    if (!empty($roomsnosay)) {
                        foreach ($roomsnosay as $item) {
                            array_push($roomsnosaystr, $item['groupid']);
                        }
                    }
                    $logindata = [
                        'member' => $member,
                        'time' => $time,
                        'token' => mt_rand(1000, 9999) . $member['password'],
                        'wsurl' => $wsurl,
                        // 'qrcode' => $qrcode,
                        'domain' => $domain,
                        'imcode' => $imcode,
                        'title' => $title,
                        'head_domain' => $head_domain,
                        'ip_info' => $ip_data_json,
                        'ip' => $real_ip,
                        'game_rule_text' => $game_rule_text,
                        'notice' => $notice,
                        'notice_status' => $notice_status,
                        'user_type' => $user_type,
                        'roomsnosay' => implode(",", $roomsnosaystr)
                    ];
                    return ['code' => 200, 'msg' => '登陆成功', 'data' => $logindata];
                }
            }
        }
    }

    /**
     * @function 手机注册
     */
    public function phone_reg_auth()
    {
        $request = Request::instance();
        // $uid = common::checkLogin();
        $phone = $request->post('phone');
        $code = $request->post('code');
        // if (is_array($uid)) {
        //     return ['code' => 400, 'msg' => '登录失效'];
        // }

        //需要验证验证码
        $code = Session::get('userreg_bindphone_code' . $phone);
        $code_exp = Session::get('userreg_bindphone_code_exp' . $phone);
        $phone = Session::get('userreg_bindphone' . $phone);
        if (empty($code)) {
            return ['code' => 500, 'msg' => '请先获取验证码'];
        }
        if (!empty($code) && !empty($code_exp) && (time() - $code_exp < 120)) {
            if ((string)$code === (string)$request->post('code')) {

                return ['code' => 200, 'msg' => '验证成功', 'phone' => $phone];
            } else {
                return ['code' => 500, 'msg' => '验证码不正确'];
            }
        } else {
            return ['code' => 500, 'msg' => '验证码已过期'];
        }


    }

    /**
     * @function 手机重设密码
     */

    public function phone_forget_auth()
    {
        $request = Request::instance();
        // $uid = common::checkLogin();
        $phone = $request->post('phone');
        $code = $request->post('code');
        // if (is_array($uid)) {
        //     return ['code' => 400, 'msg' => '登录失效'];
        // }

        //需要验证验证码
        $code = Session::get('userforgetpwd_bindphone_code' . $phone);
        $code_exp = Session::get('userforgetpwd_bindphone_code_exp' . $phone);
        $phone = Session::get('userforgetpwd_bindphone' . $phone);

        if (!empty($code) && !empty($code_exp) && (time() - $code_exp < 120)) {
            if ((string)$code === (string)$request->post('code')) {

                return ['code' => 200, 'msg' => '验证成功', 'phone' => $phone];
            } else {
                return ['code' => 500, 'msg' => '验证码不正确'];
            }
        } else {
            return ['code' => 500, 'msg' => '验证码已过期'];
        }


    }


    /**
     * @function 手机注册设置密码
     */
    public function phone_reg_pwd()
    {
        $request = Request::instance();

        $phone = $request->post('phone');
        $regname = $request->post('regname');

        $user = User::where('username', $regname)->find();
        if (!empty($user)) {
            return ['code' => 500, 'msg' => '昵称已被注册。'];
        }

        $password = $request->post('password');
        $agent_id_post = intval($request->post('agent_id'));
        $agent_id = $agent_id_post == 0 ? 1 : $agent_id_post;
        // $code = $request->post('code');


        //需要验证验证码
        $code = Session::get('userreg_bindphone_code' . $phone);
        $code_exp = Session::get('userreg_bindphone_code_exp' . $phone);
        $phone = Session::get('userreg_bindphone' . $phone);

        if (!empty($code) && !empty($code_exp) && (time() - $code_exp < 120)) {
            if ((string)$code === (string)$request->post('code')) {
                //两种情况
                $user = User::where('phone', $phone)->find();

                if (empty($user)) {
                    //注册

                    //查代理
                    $agent = Agents::where('agents_id', $agent_id)->field('agents_id,name,account')->find();
                    if (empty($agent)) {
                        $agent_id_ins = 0;
                        $agents_name_ins = 0;
                        $agents_account_ins = 0;
                    } else {
                        $agent_id_ins = $agent['agents_id'];
                        $agents_name_ins = $agent['name'];;
                        $agents_account_ins = $agent['account'];;
                    }

                    $now_time = date('Y-m-d H:i:s');
                    $username = $phone;
                    $insertData = [
                        'name' => $regname,
                        'username' => $regname,
                        'password' => md5($password),
                        'reg_time' => $now_time,
                        'agents_id' => $agent_id_ins,
                        'agents_name' => $agents_name_ins,
                        'agents_account' => $agents_account_ins,
                        'last_time' => $now_time,
                        'openid' => "",
                        'unionid' => "",
                        'head' => "",
                        'agents_share_rate' => 0,
                        'user_desc' => '',
                        'xh_config' => 1,
                        'zx_max' => 10000,
                        'zx_min' => 10,
                        'phone' => $phone,
                        'phonelogin' => 1,
                        'wxchat' => '',
                        'qq' => '',
                        'bankcard' => '',
                        'extra_share' => 0,
                        'tourist' => 0,//wx
                        'score' => 0
                    ];
                    $userModel = new User();
                    $insert_id = $userModel->insert($insertData, false, true);
                    if ($insert_id > 0) {
                        return ['code' => 200, 'msg' => '注册成功'];
                    } else {
                        return ['code' => 500, 'msg' => '网络异常，请重新操作'];
                    }

                } else {
                    //只需要设置密码
                    User::where('phone', $phone)->update([
                        'password' => md5($password),
                        'phonelogin' => 1
                    ]);
                }

                return ['code' => 200, 'msg' => '验证成功', 'phone' => $phone];
            } else {
                return ['code' => 500, 'msg' => '验证码不正确'];
            }
        } else {
            return ['code' => 500, 'msg' => '验证码已过期'];
        }
    }


    /**
     * @function 手机重设密码
     */
    public function phone_forget_pwd()
    {
        $request = Request::instance();

        $phone = $request->post('phone');
        $password = $request->post('password');
        // $agent_id = $request->post('agent_id');
        // $code = $request->post('code');


        //需要验证验证码
        $code = Session::get('userforgetpwd_bindphone_code' . $phone);
        $code_exp = Session::get('userforgetpwd_bindphone_code_exp' . $phone);
        $phone = Session::get('userforgetpwd_bindphone' . $phone);
        if (!empty($code) && !empty($code_exp) && (time() - $code_exp < 120)) {
            if ((string)$code === (string)$request->post('code')) {
                //两种情况
                $user = User::where('phone', $phone)->where('phonelogin', 1)->find();

                if (empty($user)) {
                    return ['code' => 500, 'msg' => '用户不存在。'];
                } else {
                    //只需要重设密码
                    User::where('phone', $phone)->update(['password' => md5($password)]);
                }
                return ['code' => 200, 'msg' => '重设密码成功', 'phone' => $phone];
            } else {
                return ['code' => 500, 'msg' => '验证码不正确'];
            }
        } else {
            return ['code' => 500, 'msg' => '验证码已过期'];
        }
    }

    /**
     * @function 手机注册验证码
     */
    public function phone_reg_code()
    {
        $request = Request::instance();

        $phone = $request->post('phone');

        $user = User::where('phone', $phone)->find();
        if (!empty($user)) {
            if ($user['phonelogin'] == 0) {//微信用户绑定了手机，但没有设置密码
                $wx = TRUE;
            } else {//微信用户绑定了手机，设置密码,不能再注册
                return ['code' => 500, 'msg' => '手机号已被注册，如有疑问请联系客服', 'sms' => FALSE];
            }
        } else {
            $wx = FALSE;
        }

        //发送验证码
        $code = mt_rand(999, 9999);
        $res = $this->sendSmsCode($code, $phone);

        if ($res['failCount'] == 0) {
            Session::set('userreg_bindphone_code' . $phone, $code);
            Session::set('userreg_bindphone_code_exp' . $phone, time());
            Session::set('userreg_bindphone' . $phone, $phone);
            return ['code' => 200, 'msg' => '已向' . $phone . '发送验证码', 'sms' => TRUE, 'wx' => $wx];
        } else {
            return ['code' => 500, 'msg' => '验证码发送失败,请联系技术人员', 'sms' => FALSE];
        }
    }

    /**
     * @function 手机忘记密码验证码
     */
    public function phone_forgetpwd_code()
    {
        $request = Request::instance();

        $phone = $request->post('phone');

        $user = User::where('phone', $phone)->where('phonelogin', 1)->find();
        if (!empty($user)) {
            //发送验证码
            $code = mt_rand(999, 9999);
            $res = $this->sendSmsCode($code, $phone);

            if ($res['failCount'] == 0) {
                Session::set('userforgetpwd_bindphone_code' . $phone, $code);
                Session::set('userforgetpwd_bindphone_code_exp' . $phone, time());
                Session::set('userforgetpwd_bindphone' . $phone, $phone);
                return ['code' => 200, 'msg' => '已向' . $phone . '发送验证码', 'sms' => TRUE];
            } else {
                return ['code' => 500, 'msg' => '验证码发送失败,请联系技术人员', 'sms' => FALSE];
            }
        } else {
            return ['code' => 500, 'msg' => '手机号未被注册。', 'sms' => FALSE];
        }

    }

    /**
     * @function 手机登录
     */

    public function phone_login_auth()
    {
        $request = Request::instance();
        $phone = $request->post('phone');
        $password = $request->post('password');

        if (empty($phone) || empty($password)) {
            return ['code' => 500, 'msg' => '参数错误，登录失败', 'data' => null];
        } else {
            $member = User::where('phone', $phone)->where('password', md5($password))->find();
            if (empty($member)) {
                return ['code' => 500, 'msg' => '手机号或密码错误。', 'data' => null];
            } else {
                cookie('uid', $member['uid']);
                Session::set('uid', $member['uid']);
                $success = TRUE;
                $uid = $member['uid'];
                if ($success) {
                    User::where('uid', $uid)->update(['token' => NULL]);//更新个人信息
                    $sys_info = Domain::whereIn('type', [11, 8, 12, 9, 10, 12, 27, 30])->field('domain,type,status')->select();
                    $title = "腾龙国际";
                    $head_domain = "";
                    $wsurl = "";
                    $game_rule_text = "";
                    $notice = "";
                    $imcode = "";
                    $user_type = 3;
                    foreach ($sys_info as $item) {
                        if ($item['type'] == 11) {
                            $title = $item['domain'];
                        }
                        if ($item['type'] == 8) {
                            $head_domain = $item['domain'];
                        }
                        if ($item['type'] == 12) {
                            $wsurl = $item['domain'];
                        }
                        if ($item['type'] == 30) {
                            $qrcode = $item['domain'];
                        }
                        if ($item['type'] == 9) {
                            $game_rule_text = $item['domain'];
                        }
                        if ($item['type'] == 10) {
                            $notice = $item['domain'];
                            $notice_status = $item['status'];
                        }
                        if ($item['type'] == 27) {
                            $imcode = $item['domain'];
                        }
                    }
                    $member = Db::name('user')->field('username,name,uid,head,password,score,password,agents_id,agents_account,agents_name,xm_rate,integral,phone')->where('uid', $uid)->find();
                    $member['nickname'] = $member['name'];
                    if (!empty($member['head'])) {
                        $member['head'] = $member['head'];
                    }
                    $real_ip = empty($_SERVER['HTTP_X_REAL_IP']) ? $request->ip() : $_SERVER['HTTP_X_REAL_IP'];
                    $ip_data_json = common::http_request("http://ip.taobao.com/service/getIpInfo.php?ip=" . $real_ip, null, 3);
                    $ip_data = json_decode($ip_data_json, true);
                    if ($user_type != 1) {
                        $insert_data = [
                            'uid' => $uid,
                            'username' => $member['username'],
                            'name' => $member['name'],
                            'user_type' => 0,
                            'ip_info' => empty($ip_data['data']) ? "" : json_encode($ip_data['data']),
                            'ip' => $real_ip,
                            'mktime' => time(),
                            'agents_id' => $member['agents_id'],
                            'agents_account' => $member['agents_account'],
                            'agents_name' => $member['agents_name']
                        ];
                        Db::name('user_login_info')->insert($insert_data);
                    }
                    $time = time();
                    $domain = 'http://' . $_SERVER['HTTP_HOST'];
                    $roomsnosay = System::where('nosay', 1)->field('groupid')->select();
                    $roomsnosaystr = [];
                    if (!empty($roomsnosay)) {
                        foreach ($roomsnosay as $item) {
                            array_push($roomsnosaystr, $item['groupid']);
                        }
                    }
                    $logindata = [
                        'member' => $member,
                        'time' => $time,
                        'token' => mt_rand(1000, 9999) . $member['password'],
                        'wsurl' => $wsurl,
                        //'qrcode' => $qrcode,
                        'domain' => $domain,
                        'imcode' => $imcode,
                        'title' => $title,
                        'head_domain' => $head_domain,
                        'ip_info' => $ip_data_json,
                        'ip' => $real_ip,
                        'game_rule_text' => $game_rule_text,
                        'notice' => $notice,
                        'notice_status'=>$notice_status,
                        'user_type' => $user_type,
                        'roomsnosay' => implode(",", $roomsnosaystr)
                    ];
                    return ['code' => 200, 'msg' => '登陆成功', 'data' => $logindata];
                }
            }
        }
    }

    /**
     * @function 微信登陆授权
     */
    public function wx_login_auth()
    {
        //获取业务域名 appid appsecret
        $authdomain = Domain::where('type', 21)->field('domain')->find();
        $appid = Domain::where('type', 22)->field('domain')->find();
        $appsecret = Domain::where('type', 23)->field('domain')->find();
        $domain = 'http://' . $authdomain['domain'];

        $request = Request::instance();
        $code = $request->post('code');
        $agent_id = $request->post('agent_id');

        $agent = Agents::where('agents_id', $agent_id)->field('agents_id,name,account')->find();
        if (empty($agent)) {
            return ['code' => 500, 'msg' => '代理不存在,请联系代理索要新的推广码'];
        }

        $OAUTH2 = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid['domain'] . '&secret=' . $appsecret['domain'] . '&code=' . $code . '&grant_type=authorization_code';

        $authResult = $this->curl_get_https($OAUTH2);
        $authResultJson = json_decode($authResult, 1);
        if (!empty($authResultJson['errcode'])) {
            return "errorcode:" . $authResultJson['errcode'];
        }
        $access_token = $authResultJson['access_token'];
        $openid = $authResultJson['openid'];
        //获取用户信息

        $USERINFO = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';

        $userResult = $this->curl_get_https($USERINFO);
        $userResultJson = json_decode($userResult, 1);

        $openid = $userResultJson["openid"];
        $name = $userResultJson["nickname"];
        $unionid = "";
        if (!empty($userResultJson["unionid"])) {
            $unionid = $userResultJson["unionid"];
        }
        $head = $userResultJson["headimgurl"];

        $user_type = 3;
        if ($unionid == "") {//没有unionid 只能用openid判断
            $member = User::where('openid', $openid)->field('uid,status,name')->find();
        } else {//有unionid 先用unionid 再用openid
            $member = User::where('unionid', $unionid)->field('uid,status,name')->find();
            if (empty($member)) {
                $member = User::where('openid', $openid)->field('uid,status,name')->find();
            }
        }
        $now_day = date('Y-m-d');
        if (!empty($member)) {
            if ($member['status'] == 1) {
                return ['code' => 500, 'msg' => '该账号已被禁用'];
            }
            $uid = $member['uid'];
            // User::where('uid', $uid)->update(['head' => $head,'name' => $name]);//更新个人信息
            if ($openid != "") {
                User::where('uid', $uid)->update(['openid' => $openid]);//更新个人信息
            }
            if ($unionid != "") {
                User::where('uid', $uid)->update(['unionid' => $unionid]);//更新个人信息
            }
            Session::set('uid', $uid);
            cookie('uid', $uid);
            $success = TRUE;
            $uid = $uid;
        } else {
            //先判断是否username重名
            $u = User::where('username', $name)->field('uid')->find();
            $now_time = date('Y-m-d H:i:s');
            
            if (!empty($u)) {
                //重命名$name
                $uniqid = md5($name . '_' . $now_time);
                $suffix = substr($uniqid, 1, 3);
                $name = $name . '_' . $suffix;
            }
            //查代理
            
            $agent_id_ins = $agent['agents_id'];
            $agents_name_ins = $agent['name'];;
            $agents_account_ins = $agent['account'];;
            
            $insertData = [
                'name' => $name,
                'username' => $name,
                'password' => md5($name.$now_day),
                'reg_time' => $now_time,
                'agents_id' => $agent_id_ins,
                'agents_name' => $agents_name_ins,
                'agents_account' => $agents_account_ins,
                'last_time' => $now_time,
                'openid' => $openid,
                'unionid' => $unionid,
                'head' => $head,
                'agents_share_rate' => 0,
                'user_desc' => '',
                'xh_config' => 1,
                'zx_max' => 10000,
                'zx_min' => 10,
                'phone' => '',
                'wxchat' => '',
                'qq' => '',
                'bankcard' => '',
                'extra_share' => 0,
                'tourist' => 0,//wx
                'score' => 0
            ];
            $userModel = new User();
            $insert_id = $userModel->insert($insertData, false, true);
            if ($insert_id > 0) {
                cookie('uid', $insert_id);
                Session::set('uid', $insert_id);
                $success = TRUE;
                $uid = $insert_id;
            } else {
                return ['code' => 500, 'msg' => '网络异常，请重新操作'];
            }
        }
        //走登陆
        if ($success) {
            $sys_info = Domain::whereIn('type', [11, 8, 12, 9, 10, 12, 27, 30])->field('domain,type,status')->select();
            $title = "腾龙国际";
            $head_domain = "";
            $wsurl = "";
            $game_rule_text = "";
            $notice = "";
            $imcode = "";
            foreach ($sys_info as $item) {
                if ($item['type'] == 11) {
                    $title = $item['domain'];
                }
                if ($item['type'] == 8) {
                    $head_domain = $item['domain'];
                }
                if ($item['type'] == 12) {
                    $wsurl = $item['domain'];
                }
                if ($item['type'] == 30) {
                    $qrcode = $item['domain'];
                }
                if ($item['type'] == 9) {
                    $game_rule_text = $item['domain'];
                }
                if ($item['type'] == 10) {
                    $notice = $item['domain'];
                    $notice_status = $item['status'];
                }
                if ($item['type'] == 27) {
                    $imcode = $item['domain'];
                }
            }
            $member = Db::name('user')->field('username,name,uid,head,password,score,password,agents_id,agents_account,agents_name,xm_rate,integral')->where('uid', $uid)->find();
            $member['nickname'] = $member['name'];
            if (!empty($member['head'])) {
                $member['head'] = $member['head'];
            }

            $real_ip = empty($_SERVER['HTTP_X_REAL_IP']) ? $request->ip() : $_SERVER['HTTP_X_REAL_IP'];
            $ip_data_json = common::http_request("http://ip.taobao.com/service/getIpInfo.php?ip=" . $real_ip, null, 3);
            $ip_data = json_decode($ip_data_json, true);
            if ($ip_data['code'] == 0 && $user_type != 1) {
                $insert_data = [
                    'uid' => $uid,
                    'username' => $member['username'],
                    'name' => $member['name'],
                    'user_type' => 0,
                    'ip_info' => empty($ip_data['data']) ? "" : json_encode($ip_data['data']),
                    'ip' => $real_ip,
                    'mktime' => time(),
                    'agents_id' => $member['agents_id'],
                    'agents_account' => $member['agents_account'],
                    'agents_name' => $member['agents_name']
                ];
                Db::name('user_login_info')->insert($insert_data);
            }
            $time = time();
            $domain = 'http://' . $_SERVER['HTTP_HOST'];
            $roomsnosay = System::where('nosay', 1)->field('groupid')->select();
            $roomsnosaystr = [];
            if (!empty($roomsnosay)) {
                foreach ($roomsnosay as $item) {
                    array_push($roomsnosaystr, $item['groupid']);
                }
            }
            $logindata = [
                'member' => $member,
                'time' => $time,
                'token' => mt_rand(1000, 9999) . $member['password'],
                'wsurl' => $wsurl,
                // 'qrcode' => $qrcode,
                'domain' => $domain,
                'imcode' => $imcode,
                'title' => $title,
                'ip_info' => $ip_data_json,
                'ip' => $real_ip,
                'head_domain' => $head_domain,
                'game_rule_text' => $game_rule_text,
                'notice' => $notice,
                'notice_status' => $notice_status,
                'user_type' => $user_type,
                'roomsnosay' => implode(",", $roomsnosaystr)
            ];
            return ['code' => 200, 'msg' => '登陆成功', 'data' => $logindata];
        } else {
            return ['code' => 500, 'msg' => '登陆失败'];
        }
    }

    function im_unreadMessageCount()
    {
        $request = Request::instance();
        $playid = $request->post('playid');
        $channelId = $request->post('channelId');
        $sjchannelId = $request->post('sjchannelId');

        $sys_info = Domain::where('type', 28)->field('domain')->find();
        try {

            $url = $sys_info['domain'] . '/api/weitou/' . $playid . '/' . $channelId;
            $header = [
                'X-Domain:2653165'
            ];
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $url);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

            $file_contents = curl_exec($ch);

            curl_close($ch);
            $resultJson = json_decode($file_contents, 1);


            $sjurl = $sys_info['domain'] . '/api/weitou/' . $playid . '/' . $sjchannelId;

            $sjch = curl_init();

            curl_setopt($sjch, CURLOPT_URL, $sjurl);

            curl_setopt($sjch, CURLOPT_RETURNTRANSFER, 1);

            curl_setopt($sjch, CURLOPT_CONNECTTIMEOUT, 10);

            curl_setopt($sjch, CURLOPT_HTTPHEADER, $header);

            $sj_file_contents = curl_exec($sjch);

            curl_close($sjch);
            $sjresultJson = json_decode($sj_file_contents, 1);


            return ['code' => 200, 'data' => $resultJson['data'],'sj' => $sjresultJson['data']];

        } catch (Exception $e) {
            return ['code' => 500, 'msg' => '请求错误', 'data' => null];
        }
    }

    function im_login_auth()
    {
        $request = Request::instance();
        $uid = $request->post('uid');
        if (empty($uid)) {
            return ['code' => 500, 'msg' => '参数错误'];
        } else {
            $member = User::where('uid', $uid)->field('reg_time,name,head')->find();

            $im_url = Domain::where('type', 27)->field('domain')->find();
            $sys_info = Domain::where('type', 28)->field('domain')->find();
            $arr = parse_url($im_url['domain']);
            $arr_query = $this->convertUrlQuery($arr['query']);
            $playid = substr(md5($uid . $member['reg_time']), 0, 10);

            User::where('uid', $uid)->update(['playid' => $playid]);//
            try {
                if (strpos($member['head'], 'http') !== false) {

                } else {
                    $sys_info_imgpre = Domain::where('type', 8)->field('domain')->find();
                    $member['head'] = $sys_info_imgpre['domain'] . '/' . $member['head'];
                }
                $url = $sys_info['domain'] . '/api/auth/domain/' . $playid . '/' . $arr_query['id'] . '?nickname=' . urlencode($member['name']) . '&headimgurl=' . $member['head'];
                $header = [
                    'X-Domain:2653165'
                ];
                $ch = curl_init();

                curl_setopt($ch, CURLOPT_URL, $url);

                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

                $file_contents = curl_exec($ch);

                curl_close($ch);
                $resultJson = json_decode($file_contents, 1);

                if ($resultJson['code'] == 406) {
                    return ['code' => 406, 'playid' => $playid, 'data' => null];
                } else {
                    return ['code' => 200, 'toid' => $arr_query['id'], 'imdomain' => $sys_info['domain'], 'playid' => $playid, 'data' => $resultJson['data']];
                }

            } catch (Exception $e) {
                return ['code' => 500, 'msg' => '请求错误', 'data' => null];
            }

        }
    }

    function convertUrlQuery($query)
    {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }

    function curl_get_https($url)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }


    /**
     * @function 登陆验证
     */
    public function doLogin()
    {
        $request = Request::instance();
        $username = $request->post('username');
        $password = $request->post('password');
        $user_type = intval($request->post('user_type'));
        cookie('user_type', $user_type);
        $success = FALSE;
        $uid = 0;
        if ($user_type == 1) {
            $now_time = date('Y-m-d H:i:s');
            $username = 'yk' . date('mdHis');
            $insertData = [
                'name' => '游客',
                'username' => $username,
                'password' => md5($username),
                'reg_time' => $now_time,
                'agents_id' => 0,
                'agents_name' => 0,
                'agents_account' => 0,
                'last_time' => $now_time,
                'agents_share_rate' => 0,
                'user_desc' => '',
                'xh_config' => 1,
                'zx_max' => 10000,
                'zx_min' => 10,
                'phone' => '',
                'wxchat' => '',
                'qq' => '',
                'bankcard' => '',
                'extra_share' => 0,
                'tourist' => 1,
                'score' => 2000
            ];
            $userModel = new User();
            $insert_id = $userModel->insert($insertData, false, true);
            if ($insert_id > 0) {
                cookie('uid', $insert_id);
                Session::set('uid', $insert_id);
                $success = TRUE;
                $uid = $insert_id;
            } else {
                return ['code' => 500, 'msg' => '网络异常，请重新操作'];
            }

        } else {
            if (empty($username) || empty($password)) {
                return ['code' => 500, 'msg' => '用户名或密码不能为空'];
            }

            $member = User::where('username', $username)->field('uid,status')->find();
            if (!empty($member)) {
                if ($member['status'] == 1) {
                    return ['code' => 500, 'msg' => '该账号已被禁用'];
                }
                $member1 = User::where('username', $username)->where('password', md5($password))->field('uid')->find();
                if (!empty($member1)) {
                    $uid = $member1['uid'];
                    Session::set('uid', $uid);
                    cookie('uid', $uid);
                    $success = TRUE;
                    $uid = $uid;
                } else {
                    return ['code' => 500, 'msg' => '密码不正确'];
                }
            } else {
                return ['code' => 500, 'msg' => '用户名不存在'];
            }
        }

        if ($success) {
            $sys_info = Domain::whereIn('type', [11, 8, 12, 9, 10, 30])->field('domain,type,status')->select();
            $title = "腾龙国际";
            $head_domain = "";
            $wsurl = "";
            $game_rule_text = "";
            $notice = "";
            foreach ($sys_info as $item) {
                if ($item['type'] == 11) {
                    $title = $item['domain'];
                }
                if ($item['type'] == 8) {
                    $head_domain = $item['domain'];
                }
                if ($item['type'] == 12) {
                    $wsurl = $item['domain'];
                }
                if ($item['type'] == 30) {
                    $qrcode = $item['domain'];
                }
                if ($item['type'] == 9) {
                    $game_rule_text = $item['domain'];
                }
                if ($item['type'] == 10) {
                    $notice = $item['domain'];
                    $notice_status = $item['status'];
                }
            }
            $member = Db::name('user')->field('username,name,uid,head,password,score,password,agents_id,agents_account,agents_name,xm_rate,integral')->where('uid', $uid)->find();
            $member['nickname'] = $member['name'];
            if (!empty($member['head'])) {
                $member['head'] = $member['head'];
            }
            $real_ip = empty($_SERVER['HTTP_X_REAL_IP']) ? $request->ip() : $_SERVER['HTTP_X_REAL_IP'];
            $ip_data_json = common::http_request("http://ip.taobao.com/service/getIpInfo.php?ip=" . $real_ip, null, 3);
            $ip_data = json_decode($ip_data_json, true);
            if ($ip_data['code'] == 0 && $user_type != 1) {
                $insert_data = [
                    'uid' => $uid,
                    'username' => $member['username'],
                    'name' => $member['name'],
                    'user_type' => 0,
                    'ip_info' => empty($ip_data['data']) ? "" : json_encode($ip_data['data']),
                    'ip' => $real_ip,
                    'mktime' => time(),
                    'agents_id' => $member['agents_id'],
                    'agents_account' => $member['agents_account'],
                    'agents_name' => $member['agents_name']
                ];
                Db::name('user_login_info')->insert($insert_data);
            }
            $time = time();
            $domain = 'http://' . $_SERVER['HTTP_HOST'];
            $roomsnosay = System::where('nosay', 1)->field('groupid')->select();
            $roomsnosaystr = [];
            if (!empty($roomsnosay)) {
                foreach ($roomsnosay as $item) {
                    array_push($roomsnosaystr, $item['groupid']);
                }
            }
            $logindata = [
                'member' => $member,
                'time' => $time,
                'token' => mt_rand(1000, 9999) . $member['password'],
                'wsurl' => $wsurl,
                // 'qrcode' => $qrcode,
                'domain' => $domain,
                'title' => $title,
                'head_domain' => $head_domain,
                'game_rule_text' => $game_rule_text,
                'notice' => $notice,
                'notice_status' => $notice_status,
                'user_type' => $user_type,
                'ip_info' => $ip_data_json,
                'ip' => $real_ip,
                'roomsnosay' => implode(",", $roomsnosaystr)
            ];
            return ['code' => 200, 'msg' => '登陆成功', 'data' => $logindata];
        } else {
            return ['code' => 500, 'msg' => '登陆失败'];
        }


    }


    /**
     * @function 注销登陆
     */
    public function loginOut()
    {
        cookie('uid', null);
        Session::set('uid', null);
        header('Location:' . url('/login/login_view'));
        exit;
    }


    /**
     * @function 获取短信验证码
     */
    public function sendSmsCode($code, $phone)
    {
        $res = common::sendSMS($code, $phone);
        $result = json_decode($res, true);
        return $result;
    }

}